package com.bdqn.dao;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class studentDelete {
    public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, TransformerException {
        //得到DOM解析器的工厂实例
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //从DOM工厂获得DOM解析器
        DocumentBuilder db = dbf.newDocumentBuilder();
        //解析XML文档，得到一个Document对象，即DOM树
        Document doc = db.parse("ch02jd/src/ppp.xml");  //收藏信息.xml为保存手机收藏信息的xml文档
        //找到要删除的节点
        NodeList list = doc.getElementsByTagName("student");
        for (int i = 0; i < list.getLength(); i++) {
            Element brandElement = (Element) list.item(i);
            String barndName = brandElement.getAttribute("id");
            if (barndName.equals("3")) {
                brandElement.getParentNode().removeChild(brandElement);
            }
        }
        //保存XML文件
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource domSource = new DOMSource(doc);
        //设置编码类型
        transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
        StreamResult result = new StreamResult(new FileOutputStream("ch02jd/src/ppp.xml"));
        //把DOM树转换为xml文件
        transformer.transform(domSource, result);
    }
}